package com.atguigu.tingshu.common.minio.config;

import com.atguigu.tingshu.common.minio.service.impl.FileOpsServiceImpl;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Description:
 *
 * @author Yanxinhao on 2025/1/14
 */

@Configuration
@EnableConfigurationProperties(MinioProperties.class)
@ConditionalOnProperty(prefix = "minio",havingValue = "true",value = "enable")
public class MinioAutoConfiguration {

    Logger logger = LoggerFactory.getLogger(MinioAutoConfiguration.class);

    @Bean
    public MinioClient minioClient(MinioProperties properties){
        //1.创建出Minio客户端对象
        MinioClient client = MinioClient.builder()
                .endpoint(properties.getEndpointUrl())
                .credentials(properties.getAccessKey(), properties.getSecreKey())
                .build();
        //2.我们根据当前客户端对象去判断一下是否存在桶，若不存在就创建它
        // BucketExistsArgs是一个参数对象，用来判断桶是否存在
        boolean isExist = false;
        try {
            isExist = client.bucketExists(BucketExistsArgs
                    .builder()
                    .bucket(properties.getBucketName())
                    .build());
            //3.若桶不存在，我们就去创建一个桶
            if (!isExist){
                client.makeBucket(MakeBucketArgs
                        .builder()
                        .bucket(properties.getBucketName())
                        .build());
            } else {
                logger.info("Minio中桶已经存在");
            }
            return client;
        } catch (Exception e) {
            logger.error("Minio初始化失败");
            throw new RuntimeException(e);
        }
    }

    @Bean
    public FileOpsServiceImpl fileOpsService(){
        return new FileOpsServiceImpl();
    }
}